#include "LoginDialog.h"
#include "ui_LoginDialog.h"
//构造函数
LoginDialog::LoginDialog(void):ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    //连接服务器
    tcpSocket.connectToHost("127.0.0.1",8080);
    //信号和槽连接
    connect(&tcpSocket,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(&tcpSocket,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
    connect(&tcpSocket,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    connect(&tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
            this,SLOT(onError()));
}
LoginDialog::~LoginDialog(void){
    delete ui;
}
//和服务器连接成功时执行的槽函数
void LoginDialog::onConnected()
{
    ui->status->setText("在线");
    ui->connect->setEnabled(false);
}
//和服务器断开连接时执行的槽函数
void LoginDialog::onDisconnected()
{
    ui->status->setText("离线");
    ui->connect->setEnabled(true);
}
//网络异常执行的槽函数
void LoginDialog::onError()
{
    //errorString():获取网络异常的原因
    QMessageBox::critical(this,"ERROR",tcpSocket.errorString());
}
//接收消息的槽函数
void LoginDialog::onReadyRead()
{
    if(tcpSocket.bytesAvailable()){
        //接收消息
        QString buf = tcpSocket.readAll();
        if(buf=="0y"){
            QMessageBox::about(NULL, "乘客端", "注册成功！");
        }else if(buf=="0n"){
            QMessageBox::about(NULL, "乘客端", "注册失败！");
        }else if(buf=="1y"){
            emit sclose(ui->username->text());
            this->close();
        }else if(buf=="1n"){
            QMessageBox::about(NULL, "乘客端", "登录失败！");
        }else if(buf.left(2)=="7p"){
            buf.remove(2);
            QMessageBox::about(NULL, "乘客端", buf);
            //QMessageBox::about(NULL, "About", "收到无效消息:"+buf);
        }
    }
}
//处理连接按钮的槽函数
void LoginDialog::on_connect_clicked()
{
    tcpSocket.connectToHost("127.0.0.1",8080);
    ui->status->setText("在线");
    ui->connect->setEnabled(false);
}
//处理登录按钮的槽函数
void LoginDialog::on_login_clicked(void)
{
    QString msg = "1+" + ui->username->text()+"+"+ ui->passwd->text();
    tcpSocket.write(msg.toUtf8());

}
//处理注册按钮的槽函数
void LoginDialog::on_register_2_clicked(void)
{
    QString msg = "0+" + ui->username->text()+ "+" + ui->passwd->text();
    tcpSocket.write(msg.toUtf8());
}
